import React, { Component } from 'react';
import {
	StyleSheet, Image, PixelRatio, ScrollView, Alert,
	Text, View, Dimensions, TouchableOpacity,
	TextInput, Modal, TouchableHighlight, DeviceEventEmitter
} from "react-native";
import { style } from '../../../theme/style';
import ValidateDataUtil from '../../../utils/ValidateDataUtil';
import HTTP from '../../../utils/http';
import { API, API_GENERATE } from '../../../config/api.js';
import { PriceEchartsPage } from '../component/PriceEchartsPage';
import { MyListPage } from '../component/MyListPage'
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { Common } from '../../../component/common/Common.js';

const ScreenWidth = Dimensions.get('window').width;
const scale = ScreenWidth / 375;

let responseData = [];


export class SiterRecordPage extends Component {

	static navigationOptions = ({ navigation }) => {
		return {
			headerTitle: '现货价提报',
			headerTintColor: style.color.white,//
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color="#fff" />,
			headerRight: (
				<Text style={[style.head.headerRight, { opacity: 0 }]}>
					记录
				</Text >
			),
			headerStyle: style.head.headerStyle,
			headerTitleStyle: style.head.headerTitleStyle
		}
	};

	requesting;
	constructor(props) {
		super(props);
		let { applyId, goodsCateId, goodsId, goodsName, status, branchId, yesdayPrice } = props.navigation.state.params;
		this.applyId = applyId;
		this.goodsCateId = goodsCateId;
		this.goodsId = goodsId;
		this.goodsName = goodsName;
		this.status = status;
		this.branchId = branchId;
		this.yesdayPrice = yesdayPrice;
		this.state = {
			pageStatus: {
				status: 'loading' //empty
			},
			onoff: true, // 打开tab 
			numWidth: 8,
			loginBtnDisabled: true,
			data: [],
			modalVisible: false,   //提交申请成功-弹框
			price: '0.00', //建议价
			echartsData: [],
		}

	}

	//输入价格提报
	_setWidth = (val) => {
		let wLen = val ? (val.length + 1) : 0;
		this.setState({
			numWidth: wLen > 5 ? wLen : 5
		})
	}

	async componentWillMount () {
		this._getPriceDetail();
		this._getTrend();
	}

	async	componentWillUnmount () {
		DeviceEventEmitter.emit('getCallBack', { onoff: true });
	}

	//曲线图
	async _getTrend () {
		let sendData1 = {
			goodsId: this.goodsId,
			branchId: this.branchId,
		}
		let xData = [];
		let yData = [];
		let responseData1 = await HTTP.POST(API_GENERATE(API.PRICE_TREND), sendData1);
		if (responseData1) {
			responseData1.map((item, index) => {
				xData[index] = item.prodDate.split(' ')[0];
				yData[index] = item.suggestedPrice;
			})
		}
		let echartsData = [{ prodDate: xData, marketPrice: yData }];
		this.setState({
			echartsData: echartsData
		})
	}

	async _getPriceDetail1 () {
		this.setState({
			pageStatus: {
				status: 'data'
			},
		});
	}
	async _getPriceDetail () {
		responseData = await HTTP.POST(API_GENERATE(API.PRICE_DETAIL), { applyId: this.applyId, goodsCateId: this.goodsCateId, goodsId: this.goodsId });
		if (responseData) {
			this.setState({
				pageStatus: {
					status: 'data'
				},
				lastPrice: responseData.lastPrice,
				suggestedPrice: responseData.suggestedPrice
			});
		} else {
			this.setState({
				pageStatus: {
					status: 'empty',
					emptyText: '暂无商品'
				},
			});
		}
	}

	//提交
	async _priceAdd (applyId1, goodsCateId1, goodsId1, yesdayPrice1, price, status) {
		if (this.requesting) return;
		if (ValidateDataUtil.isEmpty(price)) {
			Alert.alert('请输入建议价');
			this.refs.priceInput.focus();
			return;
		}
		const exg = /^\d+(\.\d+)?$/; //输入小数点和数字
		if (!exg.exec(price)) {
			Alert.alert('请填写正确的建议价');
			this.refs.priceInput.focus();
			return;
		}
		let sendObj = {
			applyId: applyId1,
			goodsCateId: goodsCateId1,
			goodsId: goodsId1,
			//uom: uom,//币种
			//prodDate: prodDate,
			suggestedPrice: price,
			lastPrice: yesdayPrice1,
			yesdayPrice: yesdayPrice1,
			status: status
		};
		this.requesting = true;
		let responseData = await HTTP.POST(API_GENERATE(API.PRICE_ADD), sendObj);
		if (responseData) {
			this.setState({
				modalVisible: true
			})
		} else {
			this.requesting = false;
		}
	}

	// 返回上一个页面
	_goBack = () => {
		this.props.navigation.goBack();
	}

	render () {
		let { echartsData, pageStatus, onoff, numWidth, price, lastPrice } = this.state;
		let downImg = require('../../../imgs/my-siter/down.png');
		let upImg = require('../../../imgs/my-siter/up.png');
		let rightImg = require('../../../imgs/global/success.png');
		adjustmentRange = price - lastPrice;
		return (
			<View style={styles.container}>
				{
					pageStatus.status === 'data' ? (
						<View style={{ flex: 1 }}>
							<View style={styles.TitleBox}>
								<View style={{ flexDirection: 'row', alignItems: 'center' }}>
									<Text style={styles.title}>商品：</Text>
									<Text style={[styles.title, { paddingLeft: 0 * scale, width: 290 * scale }]} numberOfLines={1} ellipsizeMode='tail'>	{this.goodsName}</Text>
								</View>
							</View>
							<ScrollView>
								<View style={styles.listBox}>
									<View style={[styles.list, styles.line]}>
										<Text style={styles.listText}>上次现货价</Text>
										<TouchableOpacity style={styles.slideBox}>
											<Text style={styles.listText}>{lastPrice || '--'}</Text>
										</TouchableOpacity>
									</View>

									<View style={styles.list}>
										<Text style={styles.listText}>调整幅度</Text>
										<View style={{ flexDirection: 'row', alignItems: 'center' }}>
											<Text style={styles.listText}>{Math.abs(adjustmentRange || 0)}</Text>
											<Image source={adjustmentRange >= 0 ? upImg : downImg} style={{ marginLeft: 5 * scale }} />
										</View>
									</View>
								</View>
								{onoff ? <PriceEchartsPage data={echartsData || []} /> : null}
								<TouchableOpacity style={styles.commit} onPress={() => { this._priceAdd(this.applyId, this.goodsCateId, this.goodsId, lastPrice, price, this.status) }}>
									<Text style={styles.commitText}>提交</Text>
								</TouchableOpacity>
							</ScrollView>

							<View style={styles.bomb}>
								<Image style={styles.bombShadow} source={require('../../../imgs/my-siter/mySiterShadow.png')} />
								<Text style={styles.bombText}>请输入建议价</Text>
								<TouchableOpacity activeOpacity={1} onPress={() => { this.refs.priceInput.focus() }} >
									<View style={styles.bombBox}>
										<Text style={{
											fontSize: 20 * scale,
											color: style.color.dark
										}}>￥</Text>
										<TextInput
											ref="priceInput"
											style={[styles.priceInput, { width: numWidth * 12 * scale }]}
											placeholder={price}
											placeholderTextColor="#999"
											onChangeText={(val) => {
												if (val.indexOf('.') != -1) {
													var arrStr = val.split('.');
													if (arrStr[1].length > 2) return
												}
												this._setWidth(val);
												this.setState({
													price: val,
													loginBtnDisabled: val.length ? false : true
												})
											}}
											underlineColorAndroid='transparent'
											keyboardType='numeric'
										/>
									</View>
								</TouchableOpacity>

							</View>

							<Modal transparent={true} visible={this.state.modalVisible} onRequestClose={() => { console.log(1) }}>
								<View style={styles.modalBox}>
									<View style={styles.modalBody}>
										<Image style={styles.modalImg} source={rightImg} />
										<Text style={styles.modalText}>价格已提交</Text>
										<TouchableHighlight style={styles.modalRight} onPress={() => {
											this.setState({
												modalVisible: false
											})
										}}>
											<Text style={styles.modalRightText} onPress={() => {
												setTimeout(() => {
													this.requesting = false;
												}, 1000);
												this._goBack()
											}}>确认</Text>
										</TouchableHighlight>
									</View>
								</View>
							</Modal>
						</View>
					) : (<PageStatusIndex {...pageStatus} />)
				}
			</View>
		)
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray
	},
	TitleBox: {
		width: '100%',
		height: 92 * scale,
		backgroundColor: style.color.themeColor
	},
	title: {
		lineHeight: 42 * scale,
		height: 42,
		color: style.color.white,
		fontSize: 18 * scale,
		paddingLeft: 23 * scale,
	},
	titleLeft: {
		height: 42,
		flexDirection: 'row',
		alignItems: 'center'
	},
	listBox: {
		paddingTop: 45 * scale,
		backgroundColor: style.color.white
	},
	list: {
		flexDirection: 'row',
		paddingTop: 15 * scale,
		paddingBottom: 15 * scale,
		marginLeft: 15 * scale,
		marginRight: 15 * scale,
		alignItems: 'center',
		justifyContent: 'space-between'
	},
	listText: {
		fontSize: 13 * scale,
		color: style.color.dark
	},
	listText12: {
		fontSize: 12 * scale,
		color: style.color.dark
	},
	listText11: {
		fontSize: 11 * scale,
		color: style.color.dark
	},
	commit: {
		marginLeft: 15 * scale,
		marginRight: 15 * scale,
		height: 44 * scale,
		borderRadius: 44 * scale,
		backgroundColor: style.color.themeColor,
		marginTop: 8 * scale,
		marginBottom: 8 * scale,
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderBottomColor: style.color.gray,
		bottom: 0 * scale,
	},
	commitText: {
		lineHeight: 44 * scale,
		textAlign: 'center',
		fontSize: 18 * scale,
		color: style.color.white
	},
	bomb: {
		width: 375 * scale,
		height: 100 * scale,
		paddingLeft: 18 * scale,
		position: 'absolute',
		top: 42 * scale,
	},
	bombShadow: {
		width: 345 * scale,
		height: 97 * scale,
		position: 'absolute',
		top: 0 * scale,
		left: 15 * scale,
	},
	priceInput: {
		padding: 0,
		fontSize: 20 * scale,
		paddingRight: 5 * scale,
		color: '#444'
	},
	bombText: {
		fontSize: 13 * scale,
		color: style.color.darkGray,
		paddingLeft: 20 * scale,
		paddingTop: 16 * scale
	},
	bombBox: {
		width: 305 * scale,
		height: 41 * scale,
		borderRadius: 4 * scale,
		backgroundColor: '#EFF2F2',
		marginTop: 6 * scale,
		marginLeft: 17 * scale,
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
	},
	imgSlide: {
		width: 11 * scale,
		height: 6 * scale,
		tintColor: style.color.darkGray,
		marginLeft: 5 * scale
	},
	slideBox: {
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center'
	},
	lineHt: {
		paddingTop: 7 * scale
	},
	listActive: {
		paddingTop: 13 * scale,
		paddingBottom: 13 * scale,
		alignItems: 'flex-start'
	},
	slideHidden: {
		height: 0,
		width: 0,
		overflow: 'hidden'
	},
	rotateX180: {
		transform: [{ rotateX: '180deg' }]
	},
	line: {
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderBottomColor: style.color.border
	},
	modalBox: {
		flex: 1,
		justifyContent: 'center',
		alignItems: 'center',
		backgroundColor: 'rgba(0, 0, 0, 0.5)'
	},
	modalBody: {
		height: 175 * scale,
		width: 300 * scale,
		backgroundColor: style.color.white,
		borderRadius: 13 * scale,
		alignItems: 'center',
		overflow: 'hidden'
	},
	modalImg: {
		width: 46 * scale,
		height: 46 * scale,
		marginTop: 17 * scale,
	},
	modalRight: {
		height: 40 * scale,
		width: '100%',
		marginTop: 36 * scale,
		borderTopWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderTopColor: style.color.border,
	},
	modalText: {
		marginTop: 18 * scale,
		textAlign: 'center',
	},
	modalRightText: {
		color: style.color.themeColor,
		lineHeight: 40 * scale,
		textAlign: 'center',
		fontSize: 13 * scale
	},
	bombBody: {
		width: 300 * scale,
		paddingLeft: 30 * scale,
		paddingRight: 26 * scale,
		paddingBottom: 10 * scale,
		backgroundColor: style.color.white,
		borderRadius: 13 * scale
	},
	bombTitle: {
		fontSize: 12 * scale,
		color: style.color.darkGray,
		paddingTop: 15 * scale,
		paddingBottom: 18 * scale
	},
	bombList: {
		flexDirection: 'row',
		justifyContent: 'space-between',
		marginBottom: 24 * scale
	},
	bombImg: {
		width: 14 * scale,
		height: 14 * scale,
	},
	bombTextFont: {
		fontSize: 13 * scale,
		color: style.color.dark
	},
	selectStyle: {
		width: 13 * scale,
		height: 7 * scale,
		marginLeft: 5 * scale
	}
})